package net.netty.heart;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author 王霄
 * @date 2021/9/8 10:20
 **/
public class HeartServer {

    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(new ChannelInitializer<>() {
                        @Override
                        protected void initChannel(Channel ch) {
                            /*
                             加入一个netty 提供 IdleStateHandler
                             1. IdleStateHandler 是netty 提供的处理空闲状态的处理器
                             2. long readerIdleTime : 表示多长时间没有读, 就会发送一个心跳检测包检测是否连接
                             3. long writerIdleTime : 表示多长时间没有写, 就会发送一个心跳检测包检测是否连接
                             4. long allIdleTime : 表示多长时间没有读写, 就会发送一个心跳检测包检测是否连接
                             5. 文档说明 triggers an {@link IdleStateEvent} when a {@link Channel} has not performed read, write, or both operation for a while.
                             6. 当 IdleStateEvent 触发后 , 就会传递给管道 的下一个handler去处理 通过调用(触发)下一个handler 的 userEventTiggered ,
                              在该方法中去处理 IdleStateEvent(读空闲，写空闲，读写空闲)
                             */
                            ch.pipeline().addLast(new IdleStateHandler(5, 10, 15, TimeUnit.SECONDS));
                            ch.pipeline().addLast(new HeartHandle());
                        }
                    });
            ChannelFuture future = bootstrap.bind(8888).sync();
            if (future.isSuccess()) {
                System.out.println("服务器启动成功");
            }
            future.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

}
